package com.yunquan.ohana.dialog

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.appcompat.app.AppCompatDialog
import androidx.databinding.DataBindingUtil
import com.yunquan.ohana.R
import com.yunquan.ohana.databinding.DialogTipBinding
import com.yunquan.ohana.utils.StringUtils

class TipDialog(context: Context) : AppCompatDialog(context) {
    private lateinit var binding: DialogTipBinding
    private var mListener: OnDialogClickListener? = null

    private var mTitle: String? = null
    private var mMessage: String? = null
    private var mLeftBtn: String? = null
    private var mRightBtn: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setCanceledOnTouchOutside(false)
        binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.dialog_tip, null, false)
        setContentView(binding.root)
        val params = window?.attributes
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params
        window?.setGravity(Gravity.CENTER)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        initView()
    }

    private fun initView() {
        if (StringUtils.isEmpty(mTitle)) {
            binding.tvTitle.visibility = View.GONE
        } else {
            binding.tvTitle.visibility = View.VISIBLE
            binding.tvTitle.text = mTitle
        }
        if (StringUtils.isEmpty(mMessage)) {
            binding.tvMessage.visibility = View.GONE
        } else {
            binding.tvMessage.visibility = View.VISIBLE
            binding.tvMessage.text = mMessage
        }
        mLeftBtn?.let {
            binding.btnCancel.text = it
        }
        mRightBtn?.let {
            binding.btnOk.text = it
        }

        binding.btnCancel.setOnClickListener {
            dismiss()
            mListener?.onLeftClick()
        }
        binding.btnOk.setOnClickListener {
            dismiss()
            mListener?.onRightClick()
        }
    }

    fun setTitle(title: String) {
        this.mTitle = title
    }

    fun setMessage(message: String) {
        this.mMessage = message
    }

    fun setLeftBtn(text: String) {
        this.mLeftBtn = text
    }

    fun setRightBtn(text: String) {
        this.mRightBtn = text
    }

    fun setOnDialogClickListener(listener: OnDialogClickListener) {
        mListener = listener
    }

    open class OnDialogClickListener {
        open fun onRightClick() {}
        open fun onLeftClick() {}
    }
}